<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }" class="login-wrapper">
        <div slot="header">
            <span>请登录账号</span>
        </div>
        <el-form :model="form" ref="loginRef" label-width="80px" :inline="false" size="normal">
            <el-form-item label="用户">
                <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码">
                <el-input type="password" v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit('loginRef')">登录</el-button>
                <el-button @click="resetForm('loginRef')">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>
<script>
import { Message } from 'element-ui'
export default {
    data() {
        return {
            form: {
                username: 'admin',
                password: 'admin'
            },
            timer: '',//定时器
        }
    },
    methods: {
        // 登录
        onSubmit(formName) {
            // this.$refs[formName].validate((valid) => {
            //   if (valid) {
            //     this.$http.login({username:this.form.username.trim(),password:this.form.password.trim()}).then(res=>{
            //         console.log(res);
            //     })
            //   } else {
            //     console.log('error submit!!');
            //     return false;
            //   }
            // })
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    const res = await this.$http.login({ username: this.form.username.trim(), password: this.form.password.trim() })
                    // console.log(res);
                    // 保存一下后台返回的token
                    // localStorage.setItem('token',res.data.message.token)
                    // localStorage.setItem('userInfo',res.data.message.token)
                    Message({
                        type: 'success',
                        message: '登陆成功，即将跳转到首页...',
                        duration: 1000
                    })
                    this.timer = setTimeout(() => {
                        this.$router.push('/')
                    }, 1000);
                } else {
                    console.log('error submit!!');
                    return false;
                }
            })
        },
        // 重置
        resetForm(formName) {
            // alert(1)
            // this.$refs[formName].resetFields();
            this.form.username = ''
            this.form.password = ''
        },
        beforeDestroy() {
            clearTimeout(this.timer)
        },
    }
}
</script>
<style lang="scss" scoped>
.login-wrapper {
    width: 25rem;
    margin: 100px auto;
}
</style>